#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#include <CoreServices/CoreServices.h> 

char *bin_path = NULL;

void my_callback( 
	ConstFSEventStreamRef streamRef, 
	void *clientCallBackInfo, 
	size_t numEvents, 
	void *eventPaths, 
	const FSEventStreamEventFlags eventFlags[], 
	const FSEventStreamEventId eventIds[]) 
{ 
	int status;
        extern char **environ;
	pid_t pid;

	pid = fork();

	char *argv[2] = {bin_path, NULL};
	if (pid == 0) { // child
		if(execve(bin_path, argv, environ) < 0) {
			perror("execve");
			exit(1);
   		}
	} else // parent
		wait(&status);
}

int main(int argc, char **argv) {
	int n_args = argc - 2;
	void *callbackInfo = NULL; 
	bin_path = argv[2];

	CFStringRef mypath = CFStringCreateWithCString(NULL, argv[1], kCFStringEncodingUTF8); 
	CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&mypath, 1, NULL);

	//CFArrayRef pathsToWatch = CFStringCreateArrayBySeparatingStrings (NULL, mypath, CFSTR(":"));

	CFAbsoluteTime latency = 1.0;
	FSEventStreamRef stream = FSEventStreamCreate(NULL,
		&my_callback,
		callbackInfo,
		pathsToWatch,
		kFSEventStreamEventIdSinceNow,
		latency,
		kFSEventStreamCreateFlagNone
	); 

	FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); 
	FSEventStreamStart(stream);
	CFRunLoopRun();

	return 0;
}
